#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "flowscene.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
  , scene_(NULL)
{
    ui->setupUi(this);
    scene_ = new FlowScene();
    ui->graphicsView->setScene(scene_);
    QTimer::singleShot(10,[=](){
        startup();
    });

}

MainWindow::~MainWindow()
{
    if(scene_){
        delete scene_;
    }
    delete ui;
}

void MainWindow::startup()
{
    uiaddional();
    loadalib();
    slotFunc();
    startupStrategy();

}

void MainWindow::uiaddional()
{
    lbParams[0] = ui->lbParam0;
    lbParams[1] = ui->lbParam1;
    lbParams[2] = ui->lbParam2;
    lbParams[3] = ui->lbParam3;
    lbParams[4] = ui->lbParam4;
    lbParams[5] = ui->lbParam5;
    leParam[0] = ui->leParam0;
    leParam[1] = ui->leParam1;
    leParam[2] = ui->leParam2;
    leParam[3] = ui->leParam3;
    leParam[4] = ui->leParam4;
    leParam[5] = ui->leParam5;
    lbNexts[0] = ui->lbNext0;
    lbNexts[1] = ui->lbNext1;
    lbNexts[2] = ui->lbNext2;
    lbNexts[3] = ui->lbNext3;
    lbNexts[4] = ui->lbNext4;
    lbNexts[5] = ui->lbNext5;
    cbNext[0] = ui->cbNext0;
    cbNext[1] = ui->cbNext1;
    cbNext[2] = ui->cbNext2;
    cbNext[3] = ui->cbNext3;
    cbNext[4] = ui->cbNext4;
    cbNext[5] = ui->cbNext5;
}

void MainWindow::loadalib()
{
    QFile alfile(":/actionlib.json");
    if(alfile.open(QFile::ReadOnly) == false){
        qInfo()<<"alfile open failed";
    }
    QByteArray fdata = alfile.readAll();
    QJsonParseError jerr;
    QJsonDocument doc = QJsonDocument::fromJson(fdata,&jerr);
    QJsonObject jobj = doc.object();
    QJsonArray jarr = jobj.value("actions").toArray();
    foreach (QJsonValue jval, jarr) {
        QJsonObject jsub = jval.toObject();
        actionlib_.insert(strValue(jsub,"name"),jsub);
    }
    ui->cbActions->addItems(actionlib_.keys());
}

void MainWindow::slotFunc()
{
    connect(scene_,&FlowScene::sigSelceted,[=](){
        loadDetailFromSelected();
    });
    connect(ui->cbActions,&QComboBox::currentTextChanged,[=](const QString& text){

    });
    connect(ui->leId,&QLineEdit::editingFinished,[=](){
        QString newid = ui->leId->text().trimmed();
        if(newid.startsWith("Void#")){
            qInfo()<<"hey!\"Void#\" is reserved.";
            ui->leId->setText(scene_->getSelectedId());
            return;
        }
        if(newid == scene_->getSelectedId()) return;
        scene_->renameSelectedId(newid);
    });
}

void MainWindow::startupStrategy()
{
    //采取类似Sublime免退出提示的方式
    //已保存的没有临时文件，保存时删掉临时文件,
    //有临时文件都是未保存状态
    //全无的意思是全新，新建新文件
    QSettings setting("jinzeyu.cn","BetaZhu");
    //修改的目标文件路径.
    QString targetFile = setting.value("targetFile").toString();
    //临时文件位置.
    QString tempFile = setting.value("tempFile",":/betazhu.json").toString();

    if(tempFile.isEmpty()==false && QFile::exists(tempFile))
    {
        if(loadFromFile(tempFile)) return;
        QMessageBox::warning(this,tr("error"),
                             tr("load file failed.(%1)").arg(tempFile));
        tempFile.clear();
    }
    if(targetFile.isEmpty()==false && QFile::exists(targetFile))
    {
        if(loadFromFile(targetFile)) return;
        QMessageBox::warning(this,tr("error"),
                             tr("load file failed.(%1)").arg(targetFile));
    }
    createNew();
}

bool MainWindow::loadFromFile(QString filePath)
{
    QFile flowJson(filePath);
    if(flowJson.open(QFile::ReadOnly) == false){
        qInfo()<<"flowJson open failed:"<<filePath;
        return false;
    }
    QByteArray fdata = flowJson.readAll();

    QJsonParseError jerr;
    QJsonDocument doc = QJsonDocument::fromJson(fdata,&jerr);
    if(jerr.error != QJsonParseError::NoError)
    {
        qInfo()<<"parse flowJson failed:"<<jerr.errorString();
        return false;
    }
    if(doc.isObject()==false)
    {
        qInfo()<<"error json, root not object.";
        return false;
    }
    QJsonObject jobj = doc.object();
    if(jobj.contains("actions")==false || jobj.contains("start")==false){
        qInfo()<<"error json, keys imcomplete.";
        return false;
    }

    return scene_->loadItems(jobj.value("actions").toArray(),
                             jobj.value("start").toString());
}

void MainWindow::createNew()
{
    scene_->resetItems();

}

QString MainWindow::strValue(const QJsonObject &jobj, const QString &key)
{
    QJsonValue jval = jobj.value(key);
    switch(jval.type())
    {
    case QJsonValue::Double:{
        return QString::number(jval.toInt());
    }
    case QJsonValue::String:{
        return jval.toString();
    }
    case QJsonValue::Bool:{
        return jval.toBool()?"1":"0";
    }
    default:
        return QString("");
    }
}

void MainWindow::loadDetailFromSelected()
{
    QString name = scene_->getSelectedName();
    if(name.startsWith("Void#")){
        ui->cbActions->setCurrentText("-- None --");
    }
    else {
        ui->cbActions->setCurrentText(name);
    }
    ui->leId->setText(scene_->getSelectedId());
    //界面key由actionlib获取，值从选中对象读取.
    QJsonObject preset = actionlib_.value(name);  //预设的字段在这里面
    ui->teDescription->setText(preset.value("description").toString());
    QJsonObject params = scene_->getSelectedItemParam(); //action参数.
    int idx = 0;
    //填充参数,从预置json中读取key，从params里读取值.
    QJsonArray jarr1 = preset.value("mandatory").toArray();
    foreach(QJsonValue jval, jarr1)
    {
        QString key = jval.toString();
        lbParams[idx]->setText(key+"*");
        leParam[idx]->setText(strValue(params,key));
        leParam[idx]->setEnabled(true);
        lbParams[idx]->setVisible(true);
        leParam[idx]->setVisible(true);
        ++idx;
        if(idx>=6) return;
    }
    QJsonArray jarr2 = preset.value("optional").toArray();
    foreach(QJsonValue jval, jarr2)
    {
        QString key = jval.toString();
        lbParams[idx]->setText(key);
        leParam[idx]->setText(strValue(params,key));
        leParam[idx]->setEnabled(true);
        lbParams[idx]->setVisible(true);
        leParam[idx]->setVisible(true);
        ++idx;
        if(idx>=6) return;
    }
    ui->liParam->setVisible(idx!=0);
    ui->lbParam->setVisible(idx!=0);
    for(int i=idx;i<6;i++)
    {
        lbParams[i]->setText("");
        leParam[i]->setText("");
        leParam[i]->setEnabled(false);
        lbParams[i]->setVisible(false);
        leParam[i]->setVisible(false);
    }
    //填充link, 先拿到所有id的list填充下拉列表.
    idx = 0;
    QStringList idsNow = scene_->getAllItemIds();
    QStringList ids; ids << "- None -";
    foreach(QString id, idsNow){
        if(id.startsWith("Void#"))continue;
        ids << id;
    }
    QStringList nxtIds = scene_->getSelectedItemNext();
    foreach(QString nxtid, nxtIds)
    {
        cbNext[idx]->clear();
        cbNext[idx]->addItems(ids);
        cbNext[idx]->setCurrentText(nxtid.isEmpty()?"- None -":nxtid);
        cbNext[idx]->setEnabled(true);
        lbNexts[idx]->setVisible(true);
        cbNext[idx]->setVisible(true);
        ++idx;
        if(idx>=6) return;
    }
    ui->liNext->setVisible(idx!=0);
    ui->lbNext->setVisible(idx!=0);
    for(int i=idx;i<6;i++)
    {
        cbNext[i]->clear();
        cbNext[i]->setEnabled(false);
        lbNexts[i]->setVisible(false);
        cbNext[i]->setVisible(false);
    }
}
